package cn.gailvlun.gll.presentation.chat.vm

import android.arch.lifecycle.ViewModel
import cn.gailvlun.gll.chatlib.db.ChatDB2
import cn.gailvlun.gll.net.Member
import cn.gailvlun.gll.util.ProfileUtil
import io.realm.Realm
import io.realm.RealmObject


class ModifyNickViewModel: ViewModel {

    private var realm: Realm?

    constructor() : super() {
        realm = Realm.getInstance(ChatDB2.getConfiguration())
    }

    fun save(realmObject: RealmObject) {
        realm?.executeTransaction { realm ->
            realm.insertOrUpdate(realmObject)
        }
    }

    fun getMyMemberByRoomId(roomId: Int): Member? {
        return realm!!.where(Member::class.java)
                .equalTo("room", roomId)
                .equalTo("owner.id", ProfileUtil.getUserId())
                .findFirst()
    }

    override fun onCleared() {
        realm?.close()
        realm = null

        super.onCleared()
    }
}